<?php
date_default_timezone_set('Asia/Shanghai');
use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('tcp://0.0.0.0:'.port());
Worker::$stdoutFile = 'card778.log';
$worker->count = 1;
// 进程启动后定时推送数据给客户端
$worker->onWorkerStart = function($worker){
    echo "conn start\n";
};
$worker->onConnect = function($data){
    echo "conn finsh\n";

};
$worker->onMessage = function($con,$data) use ($worker){

    $data=bin2hex($data);
    echo $data;
    if(strlen($data) < 10){
        return;
    }
    $hex = post_data($data);

    foreach($worker->connections as $connection) {
        $connection->send(hex2bin($hex));
    }

};
$worker->onClose = function($data){
    echo "close conn\n";
};
$worker->onError = function($data){
    echo "err\n";
};
function port(){
    $port = 778;//端口号
    return $port;
}
function post_data($data){
    $curl = curl_init();
    $url = "http://sign.aidegroup.cn/index.php/home/card/post";
    //设置post数据
    $post_data  =  array (
        "data"  =>  $data ,
        'port' => port(),
    ) ;
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    if(curl_errno($curl)) {
        return 'Errno'.curl_errno($curl);
    }
    curl_close($curl);
    $result = json_decode($result,true);
    return $result['hex'];

}
Worker::runAll();
